package org.py.jwt;

import io.jsonwebtoken.SignatureException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.py.common.MessageCode;
import org.py.common.MessageObject;
import org.py.common.MessageUtils;
import org.springframework.web.servlet.HandlerInterceptor;

public class SecurityInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String authHeader = request.getHeader("Authorization");

        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            MessageObject messageObject = new MessageObject();
            messageObject.setCode(MessageCode.M1002);
            messageObject.setContent("token封装在请求头中，格式为（Bearer后加空格）：Authorization：Bearer token");
            TokenUtil.responseMessage(MessageUtils.ObjectTojson(messageObject),response);
            return false;
        }else {
            String token = authHeader.substring(7);
            try {
                MessageObject messageObject = TokenUtil.validateJWT(token);
                if (messageObject != null) {
                    if (MessageCode.M1000.equals(messageObject.getCode())) {
                        return true;
                    } else {
                        TokenUtil.responseMessage(MessageUtils.ObjectTojson(messageObject), response);
                        return false;
                    }
                }
            } catch (SignatureException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
